package com.bmadmin.controller.cus;

import com.bmadmin.domain.DataAutoRunPOJO;
import com.bmadmin.domain.DataQueryItemPOJO;
import com.bmadmin.domain.DataQuickQueryPOJO;
import com.bmadmin.domain.NormalResult;
import com.bmadmin.domain.SysUsersPOJO;
import com.bmadmin.domain.TysxDomain;
import com.bmadmin.service.DataQuickQueryService;
import com.bmadmin.util.BMUtil;
import com.bmadmin.util.Constants;
import com.bmadmin.util.Util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

/**
 * Created by SEELE on 2017/12/17.
 */
@RestController
@RequestMapping("/dataQuickQuery")
public class DataQuickQueryController {
    private Logger logger = LogManager.getLogger(this.getClass().getName());

    @Autowired
    DataQuickQueryService dataQuickQueryService;

    @PostMapping(value = "/getQuickQuery",produces = "application/json")
    public NormalResult dataQuickQuery(HttpSession session,@RequestBody DataQuickQueryPOJO dataQuickQueryPOJO){
    	SysUsersPOJO user=(SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();

        if(BMUtil.isNullOrEmpty(dataQuickQueryPOJO)){
            result.setCode("9999");
            result.setMsg("传入对象为空");
            return result;
        }
        if(dataQuickQueryPOJO.getAsync()!=null&&dataQuickQueryPOJO.getAsync()==1){
        	logger.info("==========异步查询==========");
        	result=dataQuickQueryService.SaveAsyncQuery(dataQuickQueryPOJO,user);
        }else{
        	logger.info("==========同步查询==========");
            result=dataQuickQueryService.getQueryResult(dataQuickQueryPOJO);
        }
        return result;
    }

    @RequestMapping(value = "/getExcelexport", method = RequestMethod.GET)
    public ResponseEntity<byte[]> exampleDownload(String fileUUID) throws IOException {
        String filename = "D:\\soft\\nginx\\html\\hzwgs\\exportfile\\"+fileUUID+".xls";
//        String filename = "/Users/bomber/items/own/webstorm/hzwgs/exportfile/"+fileUUID+".xls";

        File file = new File(filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = new String("querysExport.xls".getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", downloadFileName);
        // application/octet-stream:  二进制流数据（最常见的文件下载）
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 201 HttpStatus.Created
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

    }
    
    @GetMapping("/getAutoList")
    public List<DataAutoRunPOJO> getAutoList(HttpSession session,DataAutoRunPOJO dataAutoRun){
    	logger.info("==========传入SQL_ID为【"+dataAutoRun.getT_sql_id()+"】==========");
    	SysUsersPOJO user=(SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
    	dataAutoRun.setT_userid(user.getU_id());
        return dataQuickQueryService.getQueryAutoList(dataAutoRun);
    }
    
    /**
     * 申请单删除
     */
    @PostMapping("/deleteAutoRun")
    public NormalResult deleteAutoRun(String t_id) {
    	String log = "异步查询记录删除>>>>>>>>>>>";
        NormalResult result = new NormalResult();
        if (BMUtil.isNullOrEmpty(t_id)) {
            result.setCode("9999");
            result.setMsg("传入申请单ID为空!");
            return result;
        }

        int retResult = dataQuickQueryService.deleteAutoRun(t_id);
        if(retResult>0){
    		result.setCode("0000");
            result.setMsg("删除成功！");
            logger.info(log+"删除成功！");
    	}else{
    		result.setCode("9999");
            result.setMsg("删除失败！");
            logger.info(log+"删除失败！");
    	}
    	return result;
    }
    
    @GetMapping("/getExcelData")
    public NormalResult getExcelData(HttpSession session,DataAutoRunPOJO dataAutoRun){
    	NormalResult result = new NormalResult();
    	logger.info("==========传入EXCEL文件名为【"+dataAutoRun.getT_excel()+"】==========");
    	if("".equals(Util.NulltoString(dataAutoRun.getT_excel()))){
    		result.setCode("9999");
            result.setMsg("参数错误：Excel文件名为空");
            logger.info("==========EXCEL文件名为空==========");
            return result;
    	}
    	String filename = "D:\\soft\\nginx\\html\\hzwgs\\exportfile\\"+dataAutoRun.getT_excel();
    	logger.info("==========EXCEL文件路径为【"+filename+"】==========");
    	File file = new File(filename);
    	if(!file.exists()){
    		result.setCode("9999");
            result.setMsg("Excel文件不存在");
            logger.info("==========Excel文件不存在==========");
            return result;
    	}

		InputStream is = null;
		Row row = null;
		try {
			// 根据新建的文件实例化输入流
			is = new FileInputStream(file.getAbsolutePath());

			// 根据版本选择创建Workbook的方式
			Workbook wb = null;
			// 根据文件名判断文件是2003版本还是2007版本
			if (BMUtil.isExcel2007(dataAutoRun.getT_excel())) {
				wb = new XSSFWorkbook(is);
			} else {
				wb = new HSSFWorkbook(is);
			}
			
			// 得到第一个shell
			Sheet sheet = wb.getSheetAt(0);
			//获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            if(rownum==0){
            	result.setCode("9999");
                result.setMsg("Excel文件中无数据");
                logger.info("==========Excel文件中无数据==========");
                return result;
            }
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();

            JSONArray jsons = new JSONArray();
            //循环行
            for (int i = 1; i < rownum; i++) {
            	JSONObject object = new JSONObject();
            	Row r = sheet.getRow(i);
                if(r !=null){
                    //循环列
                    for (int j=0;j<colnum;j++){
                    	object.put(""+row.getCell(j)+"", String.valueOf(r.getCell(j)));
                    }
                    jsons.add(object);
                }else{
                    break;
                }
            }
            result.setCode("0000");
            result.setMsg("数据获取成功");
            result.setData(jsons.toString());
            logger.info("==========Excel文件数据读取成功==========");
            return result;
		} catch (Exception e) {
			logger.error(e);
			result.setCode("9999");
            result.setMsg("Excel文件数据读取异常");
            logger.info("==========Excel文件数据读取异常==========");
            return result;
		}
    }
    
//    public static void main(String[] args) {
//    	String filename = "D:\\soft\\nginx\\html\\hzwgs\\exportfile\\6666.xls";
//    	File file = new File(filename);
//    	if(!file.exists()){
//    		System.out.println("文件不存在");
//    	}
//    	InputStream is = null;
//		Row row = null;
//		try {
//			// 根据新建的文件实例化输入流
//			is = new FileInputStream(file.getAbsolutePath());
//
//			// 根据版本选择创建Workbook的方式
//			Workbook wb = null;
//			// 根据文件名判断文件是2003版本还是2007版本
//			if (BMUtil.isExcel2007("123.xls")) {
//				wb = new XSSFWorkbook(is);
//			} else {
//				wb = new HSSFWorkbook(is);
//			}
//			
//			// 得到第一个shell
//			Sheet sheet = wb.getSheetAt(0);
//			//获取最大行数
//            int rownum = sheet.getPhysicalNumberOfRows();
//            //获取第一行
//            row = sheet.getRow(0);
//            //获取最大列数
//            int colnum = row.getPhysicalNumberOfCells();
//            JSONArray jsons = new JSONArray();
//            //循环行
//            for (int i = 1; i < rownum; i++) {
//            	JSONObject object = new JSONObject();
//            	Row r = sheet.getRow(i);
//                if(r !=null){
//                	Map map = new HashMap();
//                    //循环列
//                    for (int j=0;j<colnum;j++){
//                    	object.put(""+row.getCell(j)+"", String.valueOf(r.getCell(j)));
//                    }
//                    jsons.add(object);
//                }else{
//                    break;
//                }
//            }
//            System.out.println(jsons.toString());
//		} catch (Exception e) {
//				e.printStackTrace();
//		}
//	}

}
